/*
 * CAD System for seamlessly constructing 2D and 3D scenes with aspects and motion
 * Copyright (C) 2013 Bernhard Haumacher and others
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.haumacher.draw5d.dataflow.core;

import java.util.ArrayList;
import java.util.List;

import de.haumacher.draw5d.dataflow.Block;
import de.haumacher.draw5d.dataflow.Dependent;
import de.haumacher.draw5d.dataflow.Observable;

/**
 * {@link Dependent} aspect implementations.
 * 
 * @author <a href="mailto:haui@haumacher.de">Bernhard Haumacher</a>
 * @version $Revision: 26 $ $Author: haumacher@googlemail.com $ $Date: 2013-08-09 17:43:35 +0000 (Fri, 09 Aug 2013) $
 */
public class DependencyContainer implements Dependent {

	private final Observable _owner;

	private List<Observable> _dependencies;

	private boolean _iterating;

	/**
	 * Creates a {@link DependencyContainer}.
	 * 
	 * @param owner
	 *        The {@link Observable} that is treated as origin of dependencies managed by this class
	 *        (that is responsible for managing the inverse relations, see
	 *        {@link Observable#registerUser(Observable)}.
	 */
	public DependencyContainer(Observable owner) {
		_owner = owner;
		_dependencies = new ArrayList<Observable>();
	}

	/**
	 * Optimized version of a combination of {@link #removeDependency(Observable)} followed by
	 * {@link #addDependency(Observable)}.
	 * 
	 * @param oldValue
	 *        The dependency to remove.
	 * @param newValue
	 *        The dependency to add.
	 */
	public <T extends Observable> void exchangeDependency(Observable oldValue, Observable newValue) {
		boolean hasOldValue = oldValue != null;
		boolean hasNewValue = newValue != null;
		if (hasOldValue && hasNewValue) {
			copyIfIterating();
			int dependencyIndex = _dependencies.indexOf(oldValue);
			_dependencies.set(dependencyIndex, newValue);
			unregisterUsage(oldValue);
			registerUsage(newValue);
		} else {
			if (hasOldValue) {
				removeDependency(oldValue);
			}
			if (hasNewValue) {
				addDependency(newValue);
			}
		}
	}

	@Override
	public void addDependency(Observable dependency) {
		copyIfIterating();
		_dependencies.add(dependency);
		registerUsage(dependency);
	}

	@Override
	public void removeDependency(Observable dependency) {
		copyIfIterating();
		int index = _dependencies.lastIndexOf(dependency);
		_dependencies.remove(index);

		unregisterUsage(dependency);
	}

	private void copyIfIterating() {
		if (_iterating) {
			List<Observable> before = _dependencies;
			_dependencies = new ArrayList<Observable>(before.size() + 1);
			_dependencies.addAll(before);
			_iterating = false;
		}
	}

	protected void invalidate() {
		_owner.invalidate();
	}

	protected void registerUsage(Observable newValue) {
		newValue.registerUser(_owner);
	}

	protected void unregisterUsage(Observable oldValue) {
		oldValue.unregisterUser(_owner);
	}

	@Override
	public void foreachDependency(Block<? super Observable> block) {
		boolean before = _iterating;
		_iterating = true;
		try {
			for (Observable dependency : _dependencies) {
				block.apply(dependency);
			}
		} finally {
			if (_iterating) {
				// If a copy was allocated, all running iterations have their own copy.
				_iterating = before;
			}
		}
	}

}
